/*
 * Copyright (C) 2014 JackWu (androidzk@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * 版权所有 (C) 2014 JackWu (androidzk@163.com)
 * 
 * 本程序为自由软件：您可依据自由软件基金会所发表的 GNU 通用公共授权条款，对本程序再次发布和/或修改；
 * 无论您依据的是本授权的第三版，或（您可选的）任一日后发行的版本。
 * 
 * 本程序是基于使用目的而加以发布，然而不负任何担保责任；亦无对适售性或特定目的适用性所为的默示性担保。
 * 详情请参照 GNU 通用公共授权。
 * 
 * 您应已收到附随于本程序的 GNU 通用公共授权的副本；如果没有，请参照
 * 
 *      http://www.gnu.org/licenses/
 * 
 * 
 * Copyright (C) 2014 JackWu (androidzk@163.com)
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see
 * 
 *      http://www.gnu.org/licenses/
 */

package com.zoke.support.utils;

import java.lang.reflect.Field;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.DisplayMetrics;
import android.util.TypedValue;

import com.zoke.support.R;

/**
 * 桌面未读消息提醒工具类
 * 
 * @author JackWu (androidzk@163.com)
 */
public class BadgeNumber {
	// 小米品牌手机
	public static final String PHONE_XIAOMI = "Xiaomi";
	// 索尼品牌手机
	public static final String PHONE_SONY = "sony";
	// 三星品牌手机
	public static final String PHONE_SAMSUNG = "samsung";

	private static BadgeNumber mBadgeNum;

	// 默认圆角半径
	private static final int DEFAULT_CORNER_RADIUS_DIP = 8;
	// 中间数字的颜色
	private static final int DEFAULT_NUM_COLOR = Color.parseColor("#CCFF0000");

	private Activity mLauncher;
	private String lancherActivityClassName;
	private int mLogo;

	private Bitmap mLogoBit;

	/**
	 * 构造
	 * 
	 * @param launcherAct
	 *            必须是程序启动页
	 */
	private BadgeNumber(Activity launcherAct, int logoRes) {
		this.mLauncher = launcherAct;
		lancherActivityClassName = mLauncher.getClass().getName();
		mLogo = logoRes;
		Drawable drawable = mLauncher.getResources().getDrawable(mLogo);
		BitmapDrawable bdraw = (BitmapDrawable) drawable;
		mLogoBit = bdraw.getBitmap();
	}

	public static synchronized BadgeNumber getInstense(Activity launcherAct,
			int logoRes) {
		if (mBadgeNum == null)
			mBadgeNum = new BadgeNumber(launcherAct, logoRes);
		return mBadgeNum;
	}

	/**
	 * 显示数字
	 * 
	 * @param number
	 */
	public void sendBageNumber(int number) {
		// 将传进来的Numer控制在0-99之间
		number = number > 0 ? Math.max(0, Math.min(number, 99)) : 0;
		// 小米品牌的更新策略
		if (Build.MANUFACTURER.equalsIgnoreCase(PHONE_XIAOMI)) {
			sendToXiaoMi(number);
			return;
		}
		// 三星品牌
		if (Build.MANUFACTURER.equalsIgnoreCase(PHONE_SAMSUNG)) {
			sendToSamsumg(number);
			return;
		}
		// 索尼品牌
		if (Build.MANUFACTURER.toLowerCase().contains(PHONE_SONY)) {
			return;
		}
		// 其他品牌处理策略
		// 暂时的解决方案 未测试
		sendToOther(number);

	}

	private void sendToOther(int number) {
		// 创建快捷方式的Intent
		Intent shortcutintent = new Intent(
				"com.android.launcher.action.INSTALL_SHORTCUT");
		// 不允许重复创建
		shortcutintent.putExtra("duplicate", false);
		// 需要现实的名称
		shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
				mLauncher.getString(R.string.app_name));
		// 快捷图片(每次重绘logo生成一张新图)
		// Parcelable icon = Intent.ShortcutIconResource.fromContext(mLauncher,
		// mLogo);
		shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				createNumLogo(number));
		Intent mainIntent = new Intent(Intent.ACTION_MAIN);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		mainIntent.setClass(mLauncher, mLauncher.getClass());
		// 点击快捷图片，运行的程序主入口
		shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, mainIntent);
		// 发送广播。OK
		mLauncher.sendBroadcast(shortcutintent);
	}

	/**
	 * 生成带数字的logo
	 * 
	 * @param num
	 * @return
	 */
	private Bitmap createNumLogo(int num) {
		DisplayMetrics dm = mLauncher.getResources().getDisplayMetrics();
		// 基准屏幕密度
		float baseDensity = 1.5f;// 240dpi
		float factor = dm.density / baseDensity;
		// 初始化画布
		int iconSize = (int) mLauncher.getResources().getDimension(
				android.R.dimen.app_icon_size);
		Bitmap numIcon = Bitmap.createBitmap(iconSize, iconSize,
				Config.ARGB_8888);
		Canvas canvas = new Canvas(numIcon);

		// 拷贝图片
		Paint iconPaint = new Paint();
		iconPaint.setDither(true);// 防抖动
		iconPaint.setFilterBitmap(true);// 用来对Bitmap进行滤波处理，这样，当你选择Drawable时，会有抗锯齿的效果

		Rect src = new Rect(0, 0, mLogoBit.getWidth(), mLogoBit.getHeight());
		Rect dst = new Rect(0, 0, iconSize, iconSize);
		canvas.drawBitmap(mLogoBit, src, dst, iconPaint);

		Paint numPaint = new Paint(Paint.ANTI_ALIAS_FLAG
				| Paint.DEV_KERN_TEXT_FLAG);
		numPaint.setColor(Color.WHITE);
		numPaint.setTextSize(20f * factor);
		numPaint.setTypeface(Typeface.DEFAULT_BOLD);
		String numStr = num + "";
		int textWidth = (int) numPaint.measureText(numStr, 0, numStr.length());

		/**
		 * ----------------------------------* TODO 绘制圆角矩形背景 start
		 * ------------------------------------
		 */
		// 圆角矩形背景的宽度
		int backgroundHeight = (int) (2 * 15 * factor);
		int backgroundWidth = textWidth > backgroundHeight ? (int) (textWidth + 10 * factor)
				: backgroundHeight;

		canvas.save();// 保存状态

		ShapeDrawable drawable = getDefaultBackground(mLauncher);
		drawable.setIntrinsicHeight(backgroundHeight);
		drawable.setIntrinsicWidth(backgroundWidth);
		drawable.setBounds(0, 0, backgroundWidth, backgroundHeight);
		canvas.translate(iconSize - backgroundWidth, 0);
		drawable.draw(canvas);

		canvas.restore();// 重置为之前保存的状态

		/**
		 * ----------------------------------* TODO 绘制圆角矩形背景 end
		 * ------------------------------------
		 */
		// 绘制数字
		canvas.drawText(numStr,
				(float) (iconSize - (backgroundWidth + textWidth) / 2),
				22 * factor, numPaint);
		return numIcon;
	}

	/***
	 * 得到一个默认的背景：圆角矩形<br>
	 * <br>
	 * 使用代码来生成一个背景：相当于用<shape>的xml的背景
	 * 
	 * @return
	 */
	private ShapeDrawable getDefaultBackground(Context context) {
		// 这个是为了应对不同分辨率的手机，屏幕兼容性
		int r = dipToPixels(context, DEFAULT_CORNER_RADIUS_DIP);
		float[] outerR = new float[] { r, r, r, r, r, r, r, r };
		// 圆角矩形
		RoundRectShape rr = new RoundRectShape(outerR, null, null);
		ShapeDrawable drawable = new ShapeDrawable(rr);
		drawable.getPaint().setColor(DEFAULT_NUM_COLOR);// 设置颜色
		return drawable;
	}

	/**   **/
	public int dipToPixels(Context context, int dip) {
		Resources r = context.getResources();
		float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
				r.getDisplayMetrics());
		return (int) px;
	}

	/**
	 * 发送数字到小米手机
	 * 
	 * @param number
	 */
	private void sendToXiaoMi(int number) {
		NotificationManager nm = (NotificationManager) mLauncher
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = null;
		boolean isMiUIV6 = true;
		try {
			NotificationCompat.Builder builder = new NotificationCompat.Builder(
					mLauncher);
			builder.setContentTitle("您有" + number + "未读消息");
			builder.setTicker("您有" + number + "未读消息");
			builder.setAutoCancel(true);
			// builder.setSmallIcon(R.drawable.ic_launcher);
			builder.setDefaults(Notification.DEFAULT_LIGHTS);
			notification = builder.build();
			Class miuiNotificationClass = Class
					.forName("android.app.MiuiNotification");
			Object miuiNotification = miuiNotificationClass.newInstance();
			Field field = miuiNotification.getClass().getDeclaredField(
					"messageCount");
			field.setAccessible(true);
			field.set(miuiNotification, number + "");// 设置信息数
			field = notification.getClass().getField("extraNotification");
			field.setAccessible(true);
			field.set(notification, miuiNotification);
		} catch (Exception e) {
			e.printStackTrace();
			// miui 6之前的版本
			isMiUIV6 = false;
			Intent localIntent = new Intent(
					"android.intent.action.APPLICATION_MESSAGE_UPDATE");
			localIntent
					.putExtra(
							"android.intent.extra.update_application_component_name",
							mLauncher.getPackageName() + "/"
									+ lancherActivityClassName);
			localIntent.putExtra(
					"android.intent.extra.update_application_message_text",
					number + "");
			mLauncher.sendBroadcast(localIntent);
		} finally {
			if (notification != null && isMiUIV6) {
				// miui6以上版本需要使用通知发送
				nm.notify(101010, notification);
			}
		}
	}

	private void sendToSony(int number) {
		boolean isShow = true;
		if (number == 0)
			isShow = false;
		Intent localIntent = new Intent();
		localIntent
				.putExtra(
						"com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE",
						isShow);// 是否显示
		localIntent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
		localIntent.putExtra(
				"com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME",
				lancherActivityClassName);// 启动页
		localIntent
				.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE",
						number + "");// 数字
		localIntent.putExtra(
				"com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME",
				mLauncher.getPackageName());// 包名
		mLauncher.sendBroadcast(localIntent);
	}

	private void sendToSamsumg(int number) {
		Intent localIntent = new Intent(
				"android.intent.action.BADGE_COUNT_UPDATE");
		localIntent.putExtra("badge_count", number + "");// 数字
		localIntent.putExtra("badge_count_package_name",
				mLauncher.getPackageName());// 包名
		localIntent
				.putExtra("badge_count_class_name", lancherActivityClassName); // 启动页
		mLauncher.sendBroadcast(localIntent);
	}

}
